//
//  AddressView.m
//  uipickerView
//
//  Created by wujianqiang on 15/12/28.
//  Copyright © 2015年 wujianqiang. All rights reserved.
//

#import "AddressView.h"

@interface AddressView ()<UIPickerViewDataSource,UIPickerViewDelegate>
@property (nonatomic, strong) NSMutableArray *provinces;        //省
@property (nonatomic, strong) NSMutableArray *provincesId;      //省id
@property (nonatomic, strong) NSMutableArray *cityArray;        //市
@property (nonatomic, strong) NSMutableArray *cityArrayId;      //市id
@property (nonatomic, strong) NSMutableArray *areaArray;        //区
@property (nonatomic, strong) NSMutableArray *selectedArray;
@property (nonatomic, strong) UIToolbar *toolBar;
@property (nonatomic, strong) UIPickerView *pickerView;
@end

@implementation AddressView

- (instancetype)init:(addressPickerBlock)block{
    Myblock = block;
    self = [super init];
    if (self) {
        self.bounds = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 250, [UIScreen mainScreen].bounds.size.width, 250)];
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
        _pickerView.backgroundColor = [UIColor whiteColor];
        NSString *path = [[NSBundle mainBundle] pathForResource:@"area" ofType:@"plist"];
        NSArray *provinceArray = [[NSArray alloc] initWithContentsOfFile:path];
        [provinceArray enumerateObjectsUsingBlock:^(NSDictionary  *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.provinces addObject:obj[@"state"]];
            [self.provincesId addObject:obj[@"stateid"]];
        }];
        NSMutableArray *citys = [NSMutableArray arrayWithArray:[provinceArray firstObject][@"cities"]];
        [citys enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.cityArray addObject:obj[@"city"]];
            [self.cityArrayId addObject:obj[@"cityid"]];
            NSLog(@"%@",obj[@"cityid"]);
        }];
        self.areaArray = [NSMutableArray arrayWithArray:[citys firstObject][@"areas"]];
        [self addSubview:_pickerView];
        [self addSubview:self.toolBar];
    }
    return self;
}

#pragma mark - UIPickerViewDeleager
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component == 0) {
        return self.provinces.count;
    }else if (component == 1) {
        return self.cityArray.count;
    }else{
        return self.areaArray.count;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"area" ofType:@"plist"];
    NSArray *provinceArray = [[NSArray alloc] initWithContentsOfFile:path];
    if (component == 0) {
        self.selectedArray = provinceArray[row][@"cities"];
        [self.cityArray removeAllObjects];
        [self.cityArrayId removeAllObjects];
        [self.selectedArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.cityArray addObject:obj[@"city"]];
            [self.cityArrayId addObject:obj[@"cityid"]];
        }];
        self.areaArray = [NSMutableArray arrayWithArray:[self.selectedArray firstObject][@"areas"]];
        [pickerView reloadComponent:1];
        [pickerView reloadComponent:2];
        [pickerView selectRow:0 inComponent:1 animated:YES];
        [pickerView selectRow:0 inComponent:2 animated:YES];
    }else if (component == 1) {
        if (self.selectedArray.count == 0) {
            self.selectedArray = [provinceArray firstObject][@"cities"];
        }
        self.areaArray = [NSMutableArray arrayWithArray:[self.selectedArray objectAtIndex:row][@"areas"]];
        [pickerView reloadComponent:2];
        [pickerView selectRow:0 inComponent:2 animated:YES];
    }else{
    }
    NSInteger index = [_pickerView selectedRowInComponent:0];
    NSInteger index1 = [_pickerView selectedRowInComponent:1];
    NSInteger index2 = [_pickerView selectedRowInComponent:2];
    self.province = self.provinces[index];
    self.provinceId = _provincesId[index];
    if (self.cityArray.count != 0) {
        self.city = self.cityArray[index1];
        self.cityId = _cityArrayId[index1];
    }else{
        self.city = @"";
        self.cityId = @"";
    }
    if (self.areaArray.count != 0) {
        self.area = [self.areaArray[index2] componentsSeparatedByString:@"-"].firstObject;
        self.areaId = [self.areaArray[index2] componentsSeparatedByString:@"-"].lastObject;
    }else{
        self.area = @"";
        self.areaId = @"";
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (component == 0) {
        return self.provinces[row];
    }else if (component == 1){
        return self.cityArray[row];
    }else{
        if (self.areaArray.count != 0) {
            return [self.areaArray[row] componentsSeparatedByString:@"-"].firstObject;
        }else{
            return nil;
        }
    }
}

- (void)cancelPicker{
    self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    [UIView animateWithDuration:0.3
                     animations:^{
                         self.frame = CGRectMake(0, self.frame.origin.y+self.frame.size.height, self.frame.size.width, self.frame.size.height);
                     }
                     completion:^(BOOL finished){
                         [self removeFromSuperview];
    }];
}

#pragma mark - set/get
- (NSMutableArray *)provinces{
    if (!_provinces) {
        _provinces = [@[] mutableCopy];
    }
    return _provinces;
}

- (NSMutableArray *)provincesId{
    if (!_provincesId) {
        _provincesId = [@[] mutableCopy];
    }
    return _provincesId;
}

- (NSMutableArray *)cityArray{
    if (!_cityArray) {
        _cityArray = [@[] mutableCopy];
    }
    return _cityArray;
}

- (NSMutableArray *)cityArrayId{
    if (!_cityArrayId) {
        _cityArrayId = [@[] mutableCopy];
    }
    return _cityArrayId;
}

- (NSMutableArray *)areaArray{
    if (!_areaArray) {
        _areaArray = [@[] mutableCopy];
    }
    return _areaArray;
}

- (NSMutableArray *)selectedArray{
    if (!_selectedArray) {
        _selectedArray = [@[] mutableCopy];
    }
    return _selectedArray;
}

- (UIToolbar *)toolBar{
    if (_toolBar == nil) {
        self.toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 294, [UIScreen mainScreen].bounds.size.width, 44)];
        _toolBar.barTintColor=[UIColor whiteColor];
        UIBarButtonItem *item=[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(click:)];
        item.tag = 120;
        UIBarButtonItem *item1=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        UIBarButtonItem *item2=[[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(click:)];
        item2.tag = 121;
        _toolBar.items = @[item,item1, item2];
    }
    return _toolBar;
}

- (void)click:(UIBarButtonItem*)sender
{
    if (sender.tag == 120){
        [self cancelPicker];
    }
    if (sender.tag == 121){
        NSString *address;
        NSString *nameId;
        if ([self.province isEqualToString:@""] || self.province == nil || self.province == NULL) {
            address = @"北京北京";
            nameId = @"2|52";
        }else{
            address = [NSString stringWithFormat:@"%@%@%@",self.province,self.city,self.area];
            if ([self.areaId isEqualToString:@""]) {
                nameId = [NSString stringWithFormat:@"%@|%@",self.provinceId,self.cityId];
            }else{
                nameId = [NSString stringWithFormat:@"%@|%@|%@",self.provinceId,self.cityId,self.areaId];
            }
        }
        if (Myblock){
            Myblock(address,nameId);
        }
        [self cancelPicker];
        
    }
}

@end
